package com.zjw.zy.utils;

import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import java.util.UUID;

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/11/1 16:42
 * 后台定时任务工具类
 */
public final class WorkUtils {

    private static final String TAG = "WorkUtils";

    /**
     * 未来某时候唤醒service
     */
    public static UUID futureStartService(long mill) {

        PeriodicWorkRequest request = new PeriodicWorkRequest
                .Builder(StartServiceWork.class, java.time.Duration.ofMillis(mill)).build();

        WorkManager.getInstance(AppUtils.getApp());

        return request.getId();
    }

    public static void cancelFutureStartService(@NonNull UUID id) {
        WorkManager.getInstance(AppUtils.getApp()).cancelWorkById(id);
    }


    /**
     * 唤醒service
     */
    private static class StartServiceWork extends Worker {
        public StartServiceWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
            super(context, workerParams);
        }

        @NonNull
        @Override
        public Result doWork() {
            //启动service
            Intent service = new Intent();
            service.setAction("com.zjw.zy.service.APP_SERVICE");
            getApplicationContext().startService(service);
            return Result.success();
        }
    }

}
